<script setup lang="ts">
import { ref, reactive, computed } from 'vue';
import { type FormRules, type ComponentSize, type FormInstance, ElMessage, ElLoading, } from 'element-plus';
import { useRouter } from 'vue-router';
import service from '../service/index';
import { useTimerStore } from '../stores/timer';
const { getVerCode, createUser } = service;

// 创建 store 实例
const timerStore = useTimerStore();

// 访问 state
const timeRemaining = computed(() => timerStore.timeRemaining);

// 计算是否正在运行
const isRunning = computed(() => timerStore.timeRemaining > 0 && !timerStore.timerId);

interface RuleForm {
    email: string;
    vercode: string;
    username: string;
    password: string;
    newPassword: string;
    nickname: string;
}

const router = useRouter();

const formSize = ref<ComponentSize>('large')
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<RuleForm>({
    email: '3258379404@qq.com',
    vercode: '',
    username: 'admin',
    password: 'admin',
    newPassword: 'admin',
    nickname: 'TE',
})

const validator = (rule: any, value: any, callback: any) => {
    const emailRegex = /^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/;

    if (value === '') {
        callback(new Error('请输入邮箱'));
    } else if (!emailRegex.test(value)) {
        callback(new Error('邮箱格式不正确'));
    } else {
        callback();
    }

}

const validatePassword = (rule: any, value: any, callback: any) => {
    const { newPassword } = ruleForm;
    if (newPassword && value) {
        if (newPassword !== value) {
            callback(new Error('两次输入的密码不一致'));
        }
        callback();
    }
    callback();
}

const validateNewPassword = (rule: any, value: any, callback: any) => {
    const { password } = ruleForm;
    if (password && value) {
        if (password !== value) {
            callback(new Error('两次输入的密码不一致'));
        }
        callback();
    }
    callback();
}

const rules = reactive<FormRules<RuleForm>>({
    email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { max: 20, message: '用户名称最大长度20', trigger: 'blur' },
        { validator: validator, trigger: 'blur' },
    ],
    vercode: [
        { required: true, message: '请输入验证码', trigger: 'blur' },
        { max: 20, message: '验证码6位', trigger: 'blur' },
    ],
    username: [
        { required: true, message: '请输入用户名称', trigger: 'blur' },
        { max: 20, message: '用户名称最大长度20', trigger: 'blur' },

    ],
    password: [
        { required: true, message: '请输入用户密码', trigger: 'blur' },
        { max: 20, message: '用户名称最大长度20', trigger: 'blur' },
        { validator: validatePassword, trigger: 'blur' },
    ],
    newPassword: [
        { required: true, message: '请输入用户密码', trigger: 'blur' },
        { max: 20, message: '用户名称最大长度20', trigger: 'blur' },
        { validator: validateNewPassword, trigger: 'blur' },
    ],
    nickname: [
        { required: true, message: '请输入用户昵称', trigger: 'blur' },
        { max: 10, message: '用户名称最大长度10', trigger: 'blur' },
    ],
})

const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    formEl.validate((valid, fields) => {
        console.log(valid);
        if (valid) {
            const loading = ElLoading.service({
                lock: true,
                text: 'Loading',
                background: 'rgba(0, 0, 0, 0.7)',
            })

            createUser(ruleForm).then((res: any) => {
                loading.close();
                const data = res.data;
                if (data.code === 0) {
                    ElMessage({
                        showClose: true,
                        message: data.msg,
                        type: 'success',
                    })
                    router.push('/login')
                } else {
                    ElMessage({
                        showClose: true,
                        message: data.msg,
                        type: 'error',
                    })
                }
            }).catch(err => {
                ElMessage({
                    showClose: true,
                    message: err,
                    type: 'error',
                })
            })
        } else {
            console.log('error submit!', fields)
        }
    })
}

const goToLogin = () => {
    router.push('/login')
}

const getVercode = (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    formEl.validateField('email', (valid, fields) => {
        if (valid) {
            const { email } = ruleForm;
            getVerCode({
                email
            }).then((res: any) => {
                const data = res.data;
                if (data.code === 0) {
                    ElMessage({
                        showClose: true,
                        message: data.msg,
                        type: 'success',
                    })
                    // 调用 actions
                    timerStore.startTimer(60);
                } else {
                    ElMessage({
                        showClose: true,
                        message: data.msg,
                        type: 'error',
                    })
                }
            }).catch(err => {
                ElMessage({
                    showClose: true,
                    message: err,
                    type: 'error',
                })
            })
        }
    })
}

</script>

<template>
    <div class="container">
        <div class="card">
            <div class="title">welcome To TE's Bill</div>
            <div class="form">
                <div class="form-title"><b>注册</b></div>
                <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="auto" class="demo-ruleForm"
                    :size="formSize" status-icon>
                    <el-form-item label="邮箱：" prop="email">
                        <el-input v-model="ruleForm.email" placeholder="请输入邮箱" clearable />
                    </el-form-item>
                    <!-- <el-form-item label="验证码：" prop="vercode">
                        <el-row style="width: 100%;">
                            <el-col :span="16">
                                <el-input type="vercode" v-model="ruleForm.vercode" placeholder="请输入验证码" clearable />
                            </el-col>
                            <el-col :span="6" :offset="2">
                                <el-button :disabled="isRunning" type="primary" @click="getVercode(ruleFormRef)">{{
                    isRunning ? timeRemaining
                        : '验证码' }}</el-button>
                            </el-col>
                        </el-row>
                    </el-form-item> -->
                    <el-form-item label="账号：" prop="username">
                        <el-input v-model="ruleForm.username" placeholder="请输入账号" clearable />
                    </el-form-item>
                    <el-form-item label="密码：" prop="password">
                        <el-input type="password" show-password v-model="ruleForm.password" placeholder="请输入密码"
                            clearable />
                    </el-form-item>
                    <el-form-item label="确认密码：" prop="newPassword">
                        <el-input type="password" show-password v-model="ruleForm.newPassword" placeholder="请再次输入密码"
                            clearable />
                    </el-form-item>
                    <el-form-item label="昵称：" prop="nickname">
                        <el-input type="nickname" v-model="ruleForm.nickname" placeholder="请输入昵称" clearable />
                    </el-form-item>
                </el-form>
                <div class="btn">
                    <el-button type="primary" autocomplete="off" @click="submitForm(ruleFormRef)">注册</el-button>
                    <el-link type="primary" @click="goToLogin">返回登录</el-link>
                </div>
            </div>
        </div>

    </div>
</template>

<style lang="less" scoped>
.container {
    height: 100vh;
    background-image: linear-gradient(to bottom right, #FC466B, #3F5EFB);
    overflow: hidden;

    .card {
        margin: 200px auto;
        width: 500px;

        .title {
            text-align: center;
            font-size: 35px;
            padding: 20px;
            color: #ffffff;
            font-family: "MV Boli";
            font-weight: bold;
        }

        .form {
            background-color: #fff;
            padding: 20px;
            border-radius: 10px;

            .form-title {
                margin: 20px 0;
                text-align: center;
                font-size: 24px;
            }
        }

        .btn {
            margin: 50px 0 20px 0;
            display: flex;
            padding-left: 70px;
            justify-content: space-between;
        }
    }
}
</style>../stores/timer